<template>
    <el-drawer :model-value.sync="isDrawerShow" direction="rtl" :close-on-press-escape="false" size="645px"
        :before-close="handlePremisesCancel" :close-on-click-modal="false">
        <template #title>
            <h4>{{ handlePremisesTypeFilter(type) }}</h4>
        </template>
        <template #default>
            <el-form ref="ruleFormRef" v-loading="loading" label-position="top" :model="houseInfo" :inline="true"
                :rules="rules" :hide-required-asterisk="true" class="premises-form">
                <h3>基础信息</h3>
                <div v-if="houseInfo.auditOpinion" class="errInfo">
                    <el-icon color="#F15A4A" size="18px" class="errIcon">
                        <CircleCloseFilled />
                    </el-icon>
                    失败原因: {{ houseInfo.auditOpinion }}
                </div>

                <el-form-item label="区域" prop="areaArr">
                    <el-cascader ref="ruleFormCascader" v-model="houseInfo.areaArr" :options="commonList.regionList"
                        :disabled="type === 'VIEW' || type === 'EDIT' || isCrm" :props="houseData.optionProps" clearable
                        placeholder="请选择" @change="onChangeArea" />
                </el-form-item>
                <el-form-item label="项目名称" prop="name">
                    <HouseSearch v-if="type === 'ADD'" :current-company="false" :is-common="false" :maxlength="50"
                        show-word-limit :project-name="houseInfo.name" :area="houseInfo.areaArr" @createHouse="createHouse"
                        @onSelect="changeProjectName"></HouseSearch>
                    <BaiduSearch v-if="type === 'CREAT'" :area="areaLabel" :searcht-name="houseInfo.name" :maxlength="50"
                        show-word-limit @onBaiduSelect="onChangeBaiduHouse" @onBlurCustomize="onBaiduCustomize">
                    </BaiduSearch>
                    <el-input v-if="type === 'VIEW' || type === 'EDIT'" v-model="houseInfo.name" maxlength="50"
                        show-word-limit :disabled="type === 'VIEW' || type === 'EDIT'" placeholder="请输入" />
                </el-form-item>
                <el-form-item prop="type" label="物业类型">
                    <el-select @change="onTypeChange" v-model="houseInfo.type" filterable placeholder="请选择"
                        :disabled="type === 'VIEW' || type === 'ADD' || type==='EDIT' ||isCrm">
                        <el-option v-for="item in commonList.permiseList" :key="item.code" :label="item.name"
                            :value="item.code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="坐标点" prop="position">
                    <el-input v-model="houseInfo.position" :disabled="type === 'VIEW' || type === 'ADD' || type==='EDIT' || isCrm"
                        placeholder="请输入">
                        <template #append>
                            <a href="https://api.map.baidu.com/lbsapi/getpoint/index.html" target="_blank"
                                style="color: #999;">
                                <el-icon>
                                    <LocationInformation />
                                </el-icon>
                            </a>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model="houseInfo.address" :maxlength="100"
                        :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" type="textarea"
                        width="400px" />
                </el-form-item>

                <!-- 根据不同物业类型公式自动计算 -->
                <el-form-item label="覆盖人数" prop="coveredNum">
                    <el-input v-model="houseInfo.coveredNum" v-limitNumberBlur="{ decimal: 0, min: 0, max: 9999999 }"
                        :disabled='true' placeholder="" />
                </el-form-item>
                <el-form-item label="楼宇外观" prop="img" class="upload-box">
                    <div>
                        <el-upload v-if="type === 'CREAT' || type === 'EDIT' || isCrm" class="upload-demo" action=""
                            :show-file-list="false" :http-request="httpRequest">
                            <el-button icon="Upload">
                                上传
                            </el-button>
                            <template #tip>
                                <div v-if="type === 'CREAT' || type === 'EDIT' || isCrm" class="imgTips">
                                    支持图片格式png/jpg/gif，比例4:3，图片大小100kb～5m
                                </div>
                            </template>
                        </el-upload>
                    </div>
                </el-form-item>

                <div v-if="houseInfo.img" class="imgUpload">
                    <div class="imgInfo">
                        <el-image style="width: 48px; height: 48px;" :src="houseInfo.img" fit="fit"
                            :preview-src-list="[houseInfo.img]" />
                        <span>{{ houseInfo.imgName }}</span>
                    </div>
                    <el-icon v-if="type === 'CREAT' || type === 'EDIT' || isCrm" @click="houseInfo.img = ''">
                        <DeleteFilled />
                    </el-icon>
                </div>



                <template v-if="isShow">
                    <h3>项目信息</h3>
                    <el-form-item v-if="['11', '14', '12', '13'].includes(houseInfo.type)" label="物业费"
                        prop="managementPrice">
                        <el-input v-model="houseInfo.managementPrice" v-limitNumberBlur="{ decimal: 2, min: 0, max: 100 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入">
                            <template #append>
                                元/M²
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item v-if="!['2', '17'].includes(houseInfo.type)" label="交房时间" prop="deliveryTime">
                        <el-date-picker v-model="houseInfo.deliveryTime"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" style="width: 280px;" type="date"
                            placeholder="请选择" size="small" />
                    </el-form-item>
                    <el-form-item v-if="['11', '12'].includes(houseInfo.type)" label="房价" prop="accuratePrice">
                        <el-input v-model="houseInfo.accuratePrice" v-limitNumberBlur="{ min: 1000, max: 300000 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" type="number">
                            <template #append>
                                元/M²
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item v-if="['11', '12'].includes(houseInfo.type)" label="入住率" prop="inHouseRate">
                        <el-input v-model="houseInfo.inHouseRate" v-limitNumberBlur="{ decimal: 2, min: 70, max: 100 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入">
                            <template #append>
                                %
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item v-if="['13', '14', '15'].includes(houseInfo.type)" label="出租率" prop="lettingRate">
                        <el-input v-model="houseInfo.lettingRate" v-limitNumberBlur="{ decimal: 2, min: 0, max: 100 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入">
                            <template #append>
                                %
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item v-if="['13', '14', '15'].includes(houseInfo.type)" label="总入住企业数" prop="enterpriseNum">
                        <el-input v-model="houseInfo.enterpriseNum" v-limitNumberBlur="{ min: 1, max: 200000 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入">

                        </el-input>
                    </el-form-item>

                    <el-form-item v-if="['2'].includes(houseInfo.type)" label="客房数" prop="roomNumber">
                        <el-input @change="onroomNumber" v-model="houseInfo.roomNumber" v-limitNumberBlur="{ min: 1, max: 999999 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入">

                        </el-input>
                    </el-form-item>

                    <!-- //写字楼 园区 酒店 有楼盘等级  -->
                    <el-form-item v-if="['2', '14', '15'].includes(houseInfo.type)"
                        :label="houseInfo.type === '2' ? '酒店等级' : houseInfo.type === '14' ? '写字楼等级' : '园区等级'"
                        prop="levelCode">
                        <el-select v-if="houseInfo.type === '2'" v-model="houseInfo.levelCode" collapse-tags clearable
                            placeholder="请选择" :disabled="type === 'VIEW' || type === 'ADD' || isCrm">
                            <el-option v-for="item in commonList.hotelGradeList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select>
                        <el-select v-if="houseInfo.type === '14'" v-model="houseInfo.levelCode" collapse-tags clearable
                            placeholder="请选择" :disabled="type === 'VIEW' || type === 'ADD' || isCrm">
                            <el-option v-for="item in commonList.officeGradeList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select>
                        <el-select v-if="houseInfo.type === '15'" v-model="houseInfo.levelCode" collapse-tags clearable
                            placeholder="请选择" :disabled="type === 'VIEW' || type === 'ADD' || isCrm">
                            <el-option v-for="item in commonList.parkGradeList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>

                    <el-form-item v-if="['13', '16'].includes(houseInfo.type)"
                        :label="houseInfo.type === '13' ? '综合体品牌' : '基地品牌'" prop="brandName">
                        <el-input v-model="houseInfo.brandName" minlength="2" maxlength="50"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>

                    <el-form-item v-if="['17'].includes(houseInfo.type)" label="客单价" prop="customerPrice">
                        <el-input v-model="houseInfo.customerPrice" v-limitNumberBlur="{ min: 1, max: 999999 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>

                    <el-form-item v-if="['17'].includes(houseInfo.type)" label="客桌数" prop="customerTableNum">
                        <el-input @change="oncustomerTableNum" v-model="houseInfo.customerTableNum" v-limitNumberBlur="{ min: 1, max: 999999 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>

                    <el-form-item v-if="['13'].includes(houseInfo.type)" label="日均人流量" prop="visitorsFlowrate">
                        <el-input @change="onvisitorsFlowrate" v-model="houseInfo.visitorsFlowrate" v-limitNumberBlur="{ min: 1000, max: 1000000 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>

                    <el-form-item v-if="houseInfo.type !== '17'" label="总楼栋数" prop="buildNum">
                        <el-input v-model="houseInfo.buildNum" v-limitNumberBlur="{ min: 1, max: 1000 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" type="Number" />
                    </el-form-item>
                    <el-form-item v-if="!['17', '15', '16'].includes(houseInfo.type)" label="总单元数" prop="unitNum">
                        <el-input v-model="houseInfo.unitNum" v-limitNumberBlur="{ min: 1, max: 10000 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="总电梯数" prop="elevatorNum">
                        <el-input v-model="houseInfo.elevatorNum" v-limitNumberBlur="{ min: 1, max: 50000 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="最高楼层" prop="maxStorey">
                        <el-input v-model="houseInfo.maxStorey" v-limitNumberBlur="{ min: 0, max: 130 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="最低楼层" prop="minStorey">
                        <el-input v-model="houseInfo.minStorey" v-limitNumberBlur="{ min: 1, max: 130 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item v-if="['11', '12'].includes(houseInfo.type)" label="总户数" prop="houseNum">
                        <el-input @change="onhouseNum" v-model="houseInfo.houseNum" v-limitNumberBlur="{ min: 1, max: 200000 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>

                    <el-form-item v-if="!['2', '17'].includes(houseInfo.type)" label="平均租金" prop="rentPrice">
                        <el-input v-model="houseInfo.rentPrice" v-limitNumberBlur="{ decimal: 2, min: 10, max: 1000 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>

                    <el-form-item v-if="['11'].includes(houseInfo.type)" label="容积率" prop="cubageRate">
                        <el-input v-model="houseInfo.cubageRate" v-limitNumberBlur="{ decimal: 2, min: 0, max: 10 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item v-if="['11'].includes(houseInfo.type)" label="绿化率" prop="greeningRate">
                        <el-input v-model="houseInfo.greeningRate" v-limitNumberBlur="{ decimal: 2, min: 0, max: 100 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item v-if="!['17'].includes(houseInfo.type)" label="项目总建筑面积" prop="buildingArea">
                        <el-input v-model="houseInfo.buildingArea" v-limitNumberBlur="{ decimal: 2, min: 1, max: 99999999 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="楼盘级别" prop="buildingLevel">
                        <el-select v-model="houseInfo.buildingLevel" collapse-tags clearable placeholder="请选择"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm">
                            <el-option v-for="item in commonList.buildLevelList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="['11', '14', '12', '13'].includes(houseInfo.type)" label="开发商"
                        prop="developersName">
                        <el-input v-model="houseInfo.developersName" :disabled="type === 'VIEW' || type === 'ADD' || isCrm"
                            placeholder="请输入" />
                    </el-form-item>

                    <el-form-item label="物业公司名称" prop="management">
                        <el-input v-model="houseInfo.management" :disabled="type === 'VIEW' || type === 'ADD' || isCrm"
                            placeholder="请输入" />
                    </el-form-item>

                    <!-- <el-form-item label="地面停车位" prop="overgroundParkingNum">
                        <el-input
                            v-model="houseInfo.overgroundParkingNum"
                            v-limitNumber="{ min: 0, max: 9999 }"
                            :disabled="type === 'VIEW' || type === 'ADD'"
                            placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="地下停车位" prop="undergroundParkingNum">
                        <el-input
                            v-model="houseInfo.undergroundParkingNum"
                            v-limitNumber="{ min: 0, max: 9999 }"
                            :disabled="type === 'VIEW' || type === 'ADD'"
                            placeholder="请输入"
                        />
                    </el-form-item>
                    <el-form-item label="充电桩数" prop="chargingPileNum">
                        <el-input
                            v-model="houseInfo.chargingPileNum"
                            v-limitNumber="{ min: 0, max: 9999 }"
                            :disabled="type === 'VIEW' || type === 'ADD'"
                            placeholder="请输入"
                            type="number"
                        />
                    </el-form-item> -->
                    <el-form-item v-if="!['17'].includes(houseInfo.type)" label="总停车位" prop="parkingNum">
                        <el-input v-model="houseInfo.parkingNum" v-limitNumberBlur="{ min: 0, max: 999999 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" type="number" />
                    </el-form-item>

                    <el-form-item v-if="['11'].includes(houseInfo.type)" label="车位数配比" prop="parkingRatio">
                        <el-input v-model="houseInfo.parkingRatio" v-limitNumberBlur="{ decimal: 2, min: 0, max: 10 }"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm" placeholder="请输入" type="number" />
                    </el-form-item>
                    <el-form-item label="是否核心区" prop="isCore">
                        <el-select v-model="houseInfo.isCore" collapse-tags clearable placeholder="请选择"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm">
                            <el-option label="是" :value="1" />
                            <el-option label="否" :value="0" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="禁忌行业" prop="industry">
                        <el-select v-model="houseInfo.industry" multiple collapse-tags clearable placeholder="请选择"
                            :disabled="type === 'VIEW' || type === 'ADD' || isCrm">
                            <el-option v-for="item in commonList.industryList" :key="item.code" :label="item.name"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>

                </template>
                <div v-else class="more" @click="isShow = !isShow">
                    查看更多
                    <el-icon color="#8C8C8C" class="moreIconClass">
                        <ArrowDown />
                    </el-icon>
                </div>
            </el-form>
            <section>
                <h3>合同信息</h3>
                <CostEntryFrom v-if="isDrawerShow" ref="costEntryRef" :apply-order-id="props.applyOrderId"
                    :is-edit="type === 'EDIT'" :show-more="false"></CostEntryFrom>
            </section>
        </template>
        <template #footer>
            <div style="flex: auto;">
                <el-button @click="handlePremisesCancel">
                    取消
                </el-button>
                <el-button type="primary" :loading="dialogBtnLoading" @click="onConfirmPremises(ruleFormRef)">
                    确认
                </el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, watch, nextTick, defineEmits, defineProps, defineExpose, getCurrentInstance } from 'vue';
import { useStore } from 'vuex';
import { Upload } from '@x-tech/fe-puma-lib-upload';
import { HousePages } from './../houseManageType';
import BaiduSearch from '@/components/BaiduSearch.vue';
import HouseSearch from '@/components/HouseSearch.vue';
import CostEntryFrom from './CostEntryFrom.vue';
import { handlePremisesTypeFilter } from '@/utils/filters';

import {
    premisesAdd,
    premisesCreate,
    premisesUpdate,
    checkPremises,
    getDraftDetail,
    draftUpdate,
} from '@/api/houseManage';
import type { FormRules, FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Key } from '@element-plus/icons';
import { max } from 'lodash';

const store = useStore();
const keyNum = ref(0)
// {code: '11', name: '中高端住宅'}
// {code: '12', name: '商住楼'}
// {code: '13', name: '综合体'}
// {code: '2', name: '酒店'}
// {code: '14', name: '写字楼'}
// {code: '15', name: '园区'}
// {code: '16', name: '企业基地总部'}
// {code: '17', name: '酒楼'}

const emits = defineEmits(['changeProjectName', 'createHouse', 'onDrawerShow']);
const props = defineProps({
    type: {
        type: String,
        default: 'ADD',
    },
    isDrawerShow: {
        type: Boolean,
        default: false,
    },
    applyOrderId: {
        type: String,
        default: '',
    },
    premiseId: {
        type: String,
        default: '',
    },
    transferId: {
        type: String,
        default: '',
    },
    buildSource: {
        type: String,
        default: ''
    }
});

const isCrm = ref(props.buildSource === 'crm')
watch(() => props.buildSource, (val) => {
    isCrm.value = val === 'crm'
})
const ruleFormCascader: any = ref(null);
const ruleFormRef: any = ref<FormInstance>();
const costEntryRef: any = ref<FormInstance>();
const areaLabel = ref('');
const houseData = reactive(new HousePages());
const houseInfo = reactive(houseData.houseInfo);
const commonList: any = computed(() => store.state.app.common.CommonList);
const supplierAreaList: any = computed(() => store.state.app.common.supplierAreaList);
const isShow = ref(true);
const dialogBtnLoading = ref(false);
const loading = ref(false);
const formSize = ref('large');
const premisesData = reactive({});

console.log('commonList', commonList);

const checkChinese = (rule, value, callback) => {
    if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
            callback(new Error('编码不能输入汉字!'));
        } else {
            callback();
        }
    }
    callback();
};

const rules: any = reactive<FormRules>({
    name: [{ required: true, message: '楼盘名称不能为空', trigger: 'change' }],
    buildNum: [{ required: true, message: '总楼栋数不能为空', trigger: 'change' }],
    unitNum: [{ required: true, message: '总单元数不能为空', trigger: 'change' }],
    elevatorNum: [{ required: true, message: '总电梯数不能为空', trigger: 'change' }],
    maxStorey: [{ required: true, message: '最高楼层不能为空', trigger: 'change' }],
    minStorey: [{ required: true, message: '最低楼层不能为空', trigger: 'change' }],
    houseNum: [{ required: true, message: '总户数不能为空', trigger: 'change' }],
    lettingRate: [{ required: true, message: '出租率不能为空', trigger: 'change' }],
    enterpriseNum: [{ required: true, message: '总入住企业数不能为空', trigger: 'change' }],
    roomNumber: [{ required: true, message: '客房数不能为空', trigger: 'change' }],
    levelCode: [{ required: true, message: '等级不能为空', trigger: 'change' }],
    brandName: [
        { required: true, message: '品牌名不能为空', trigger: 'change' },
        { pattern: /^.{2,50}$/, required: true, message: '品牌名2-50位字符', trigger: 'blur' }
    ],
    visitorsFlowrate: [{ required: true, message: '日均人流量不能为空', trigger: 'change' }],
    accuratePrice: [{ required: true, message: '房价不能为空', trigger: 'blur' }],
    rentPrice: [{ required: true, message: '平均租金不能为空', trigger: 'change' }],
    managementPrice: [{ required: true, message: '物业费不能为空', trigger: 'change' }],
    parkingNum: [{ required: true, message: '总停车位不能为空', trigger: 'change' }],
    parkingRatio: [{ required: true, message: '车位配比数不能为空', trigger: 'change' }],
    cubageRate: [{ required: true, message: '容积率不能为空', trigger: 'change' }],
    greeningRate: [{ required: true, message: '绿化率不能为空', trigger: 'change' }],
    buildingArea: [{ required: true, message: '总建筑面积不能为空', trigger: 'change' }],
    developersName: [
        { required: true, message: '开发商不能为空', trigger: 'change' },
        { pattern: /^.{2,50}$/, required: true, message: '开发商名称2-50位字符', trigger: 'blur' }
    ],
    management: [
        { required: true, message: '物业公司名称不能为空', trigger: 'change' },
        { pattern: /^.{2,50}$/, required: true, message: '物业公司名2-50位字符', trigger: 'blur' }
    ],
    isCore: [{ required: true, message: '是否核心区不能为空', trigger: 'change' }],

    areaArr: [{ required: true, message: '区域不能为空', trigger: 'change' }],
    type: [{ required: true, message: '物业类型不能为空', trigger: 'change' }],
    img: [{ required: true, message: '图片不能为空', trigger: 'blur' }],

    // 覆盖人数根据公司自动计算
    // coveredNum: [
    //     { required: true, message: '覆盖人数不能为空', trigger: 'blur' },
    //     { pattern: /^[1-9]\d*$/, required: true, message: '请输入正整数', trigger: 'blur' },
    // ],
    address: [{ required: true, message: '地址不能为空', trigger: 'blur' }],
    position: [
        { required: true, message: '坐标点不能为空', trigger: 'blur' },
        { validator: checkChinese, message: '坐标点不能含有中文', trigger: 'blur' },
    ],
    deliveryTime: [{ required: true, message: '交房时间不能为空', trigger: 'blur' }],
    buildingLevel: [{ required: true, message: '楼盘级别不能为空', trigger: 'blur' }],
    customerPrice: [{ required: true, message: '客单价不能为空', trigger: 'blur' }],
    customerTableNum: [{ required: true, message: '客桌数不能为空', trigger: 'blur' }],
    inHouseRate:[{ required: true, message: '入住率不能为空', trigger: 'blur' }]
});
const createHouse = (): void => {
    emits('createHouse');
};

// 校验图片宽高问题
const checkWidthAndHeight = (file: any) => {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = URL.createObjectURL(file);
        img.onload = function () {
            const width = img.width;
            const height = img.height;
            console.log('当前图片的宽高', width, height);
            console.log('当前图片的宽高', width / height);
            if (width / height > 1.1 && width / height < 1.5) {
                resolve(true);
            } else {
                ElMessage.error('图片的宽高比必须是4:3'); // 图片分辨率比例范围1.1~1.5
                reject(false);
            }
        };
    });
};
// 重置表单
const resetFields = () => {
    if (!ruleFormRef.value) {
        return;
    }
    ruleFormRef.value.resetFields();
};
// puam上传图片的方法
const judgeUpload = async (file: any): any => {
    let upl: any = null;
    if (window.XCConfig.VUE_APP_ENV === 'prod') {
        // 这里关于环境的判断，各项目跟据自身情况修改
        upl = Upload.createProdUpload();
    } else if (window.XCConfig.VUE_APP_ENV === 'test') {
        upl = Upload.createTestUpload();
    } else if (window.XCConfig.VUE_APP_ENV === 'pre') {
        upl = Upload.createPreUpload();
    } else {
        upl = Upload.createDevUpload();
    }
    const imgRA = /image/g;
    if (!imgRA.test(file.type)) {
        ElMessage.error('请上传图片');
        return false;
    } else if (file.size / 1024 < 100) {
        ElMessage.error('上传的图片大小不能小于100KB');
        return false;
    } else if (file.size / 1024 / 1024 > 5) {
        ElMessage.error('上传的图片大小不能大于5M');
        return false;
    }

    await checkWidthAndHeight(file);
    houseInfo.imgName = file.name;
    return upl.uploadImg({ file, size: 's', isEncrypt: false });

    // return upl.upload(file, false);
};

// 返回上传的图片
const httpRequest = async (rawFile: any) => {
    const result = await judgeUpload(rawFile.file);
    if (result) {
        houseInfo.img = result;
    }
};
const resetFormData = (): void => {
    Object.keys(houseInfo).forEach((key) => {
        houseInfo[key] = '';
    });
};
const handlePremisesCancel = (): void => {
    resetFormData();
    resetFields();
    emits('onDrawerShow');
};



function resetHouseInfo() {
    houseInfo.applyOrderId = '';
    houseInfo.accuratePrice = '';
    // houseInfo.address = '';
    // houseInfo.areaArr = [];
    houseInfo.area = 0;
    houseInfo.buildNum = '';
    houseInfo.chargingPileNum = '';
    houseInfo.city = 0;
    // houseInfo.coveredNum = '';
    houseInfo.img = '';
    houseInfo.inHouseRate = '';
    houseInfo.managementPrice = '';
    houseInfo.maxStorey = '';
    houseInfo.minStorey = '';
    houseInfo.lettingRate = '';
    // houseInfo.name = '';
    houseInfo.overgroundParkingNum = '';
    houseInfo.positionLat = '';
    houseInfo.positionLng = '';
    // houseInfo.position = '';
    houseInfo.premisesId = '';
    houseInfo.province = 0;
    houseInfo.status = '';
    houseInfo.tabooCode = '';
    // houseInfo.type = '';
    houseInfo.undergroundParkingNum = '';

    houseInfo.unitNum = '';
    houseInfo.deliveryTime = '';
    houseInfo.baidu = false;
    houseInfo.industry = [];
    houseInfo.imgName = '';
    houseInfo.auditImg = '';
    houseInfo.houseNum = '';
    houseInfo.enterpriseNum = null;
    houseInfo.roomNumber = null;
    houseInfo.levelCode = '';
    houseInfo.levelParent = '';
    houseInfo.brandName = '';
    houseInfo.customerPrice = '';
    houseInfo.customerTableNum = '';
    houseInfo.visitorsFlowrate = '';

    houseInfo.rentPrice = '';
    houseInfo.parkingRatio = '';
    houseInfo.greeningRate = '';
    houseInfo.cubageRate = '';
    houseInfo.buildingArea = '';
    houseInfo.developersName = '';
    houseInfo.management = '';
    houseInfo.buildingLevel = '';
    houseInfo.isCore = 1;
}

watch(() => houseInfo.buildingArea, (val) => {

    if (!val) return;
    if(isNaN(val)) return;
    if (houseInfo.type === '12' || houseInfo.type === '14') {
        //商住楼 写字楼 覆盖人数 = 建筑面积/8*0.7 
        houseInfo.coveredNum = (+val / 8 * 0.7).toFixed(0)
    }
    if (houseInfo.type === '15' || houseInfo.type === '16') {
        //园区 企业基地总部 覆盖人数 = 建筑面积/8*0.7 
        houseInfo.coveredNum = (+val / 15).toFixed(0)
    }
})

function onvisitorsFlowrate(val:any) {
    if (!val) return;
    if(isNaN(val)) return;
    if (houseInfo.type === '13') {
        //综合体 覆盖人数 = 日均人流量 
        houseInfo.coveredNum = (+val * 0.2).toFixed(0)
    }
}
function onhouseNum(val:any){
    if (!val) return;
    if(isNaN(val)) return;
    if (houseInfo.type === '11') {
        //住宅 ~ 覆盖人数=总户数*2.7*入住率（入住率统一按90%计算，默认就取90%）
        houseInfo.coveredNum = (+val * 2.7 * 0.9).toFixed(0)
    }
}

function oncustomerTableNum(val:any){
    if (!val) return;
    if(isNaN(val)) return;
    if (houseInfo.type === '17') {
        houseInfo.coveredNum = +val * 10
    }
}

function onroomNumber(val:any){
    if (!val) return;
    if(isNaN(val)) return;
    if (houseInfo.type === '2') {
        houseInfo.coveredNum = +val * 2;
    }
}

// 点击创建和新建楼盘的操作
const onConfirmPremises = async (formEl: FormInstance | undefined): Promise<void> => {
    console.log(costEntryRef.value);
    if (props.type !== 'VIEW') {
        [houseInfo.province, houseInfo.city, houseInfo.area] = houseInfo.areaArr || [];
        [houseInfo.positionLng, houseInfo.positionLat] = houseInfo.position ? houseInfo.position.split(',') : [];
        houseInfo.tabooCode = houseInfo.industry ? houseInfo.industry.join(',') : '';
        const keysArr = {
            accuratePrice: '精确房价',
            inHouseRate: '入住率',
            buildNum: '楼栋数',
            unitNum: '单元数',
            elevatorNum: '总电梯数',
            maxStorey: '最高楼层',
            overgroundParkingNum: '地上车位数',
            undergroundParkingNum: '地下车位数',
            chargingPileNum: '充电桩数',
        };
        const reg = /^\d+$/;
        const Key = Object.keys(keysArr).find((key) => houseInfo[key] && !reg.test(houseInfo[key]));
        if (Key) {
            ElMessage.error(`${keysArr[Key]}只能为正整数`);
            return false;
        }

        if (!formEl) {
            return;
        }


        // 如果是物业类型是酒店 写字楼 园区 需要传 levelParent
        if (['2', '14', '15'].includes(houseInfo.type)) {
            houseInfo.levelParent = houseInfo.type === '2' ? ' hotel_grade' : houseInfo.type === '14' ? ' office_build_grade' : 'park_grade'
        }

        await formEl.validate(async (valid, fields) => {
            if (valid) {
                dialogBtnLoading.value = true;
                try {
                    if (props.type === 'ADD') {
                        const formList = await costEntryRef.value.submitForm();
                        houseInfo.premisesContractDTOS = formList;
                        await premisesAdd(houseInfo);
                        ElMessage.success('楼盘新建成功');
                    }
                    if (props.type === 'EDIT') {
                        const formList = await costEntryRef.value.submitForm();
                        houseInfo.premisesContractDTOS = formList;
                        await (props.applyOrderId ? premisesUpdate(houseInfo) : draftUpdate(houseInfo));
                        //  await premisesUpdate(houseInfo);
                        ElMessage.success('楼盘修改成功');
                    }
                    if (props.type === 'CREAT') {
                        const formList = await costEntryRef.value.submitForm();
                        houseInfo.premisesContractDTOS = formList;
                        await premisesCreate(houseInfo);
                        houseInfo.baidu && ElMessage.success('楼盘创建成功');
                        !houseInfo.baidu && ElMessage.success('楼盘已创建，请等待审核');
                    }
                    dialogBtnLoading.value = false;
                    resetFields();
                    emits('onDrawerShow', 'confirm');
                } catch {
                    dialogBtnLoading.value = false;
                }
            } else {
                console.log('error submit!', fields);
                await costEntryRef.value.submitForm();
            }
        });
    } else {
        handlePremisesCancel();
    }
};

// 切换区域创建和新建的操作
const onChangeArea = (area: number[]): void => {
    if (props.type !== 'CREAT') {
        resetFormData();
        houseInfo.areaArr = area || [];
    } else {
        if (area) {
            const checkedNode = ruleFormCascader.value.getCheckedNodes();
            const pathLabel = checkedNode['0'].pathLabels;
            areaLabel.value = `${pathLabel[0]}${pathLabel[1]}${pathLabel[2]}`;
        } else {
            areaLabel.value = '';
        }
        houseInfo.name = '';
        houseInfo.position = '';
        houseInfo.address = '';
        houseInfo.type = '';
    }
};
// 搜索ssp已有的楼盘，选择楼盘
const changeProjectName = (premiseItem: any): void => {
    if (premiseItem.premiseId) {
        Object.assign(houseInfo, premiseItem);
        Object.assign(premisesData, premiseItem);
        houseInfo.position = `${premiseItem.positionLng},${premiseItem.positionLat}`;
        houseInfo.areaArr = [premiseItem.province, premiseItem.city, premiseItem.area];
    } else {
        const areaArr = houseInfo.areaArr;
        resetFormData();
        houseInfo.areaArr = areaArr;
    }
};
// 搜索百度楼盘选择，创建楼盘
const onChangeBaiduHouse = (value: any): void => {
    const premises = value;
    houseInfo.position = premises.point ? `${premises.point.lng},${premises.point.lat}` : '';
    houseInfo.address = premises.address;
    houseInfo.name = premises.title;
    houseInfo.type = '';
    houseInfo.baidu = true;
};
// 自定义了楼盘,失去焦点
const onBaiduCustomize = (value: string): void => {
    houseInfo.name = value;
    houseInfo.position = '';
    houseInfo.address = '';
    houseInfo.type = '';
    houseInfo.baidu = false;
    // console.log(houseInfo.baidu)
};

function onTypeChange() {
    resetHouseInfo();
}
// 监听楼盘的打开的参数
watch(
    () => props.isDrawerShow,
    async (isDrawerShow): Promise<void> => {
        if (props.isDrawerShow && props.type === 'ADD') {
            isShow.value = false;
            await nextTick();
            resetFormData();
            resetFields();
        } else {
            isShow.value = true;
        }
        if (props.isDrawerShow && (props.type === 'CREAT' || props.type === 'ADD')) {
            if (!supplierAreaList.value.length) {
                houseInfo.areaArr = [510000, 510100, 510107];
                areaLabel.value = '四川省成都市武侯区';
            } else {
                houseInfo.areaArr = supplierAreaList.value[0];
                console.log(houseInfo.areaArr);
                if (props.type === 'CREAT') {
                    await nextTick();
                    const checkedNode = ruleFormCascader.value.getCheckedNodes();
                    console.log(checkedNode);
                    const pathLabel = checkedNode['0'].pathLabels;
                    areaLabel.value = `${pathLabel[0]}${pathLabel[1]}${pathLabel[2]}`;
                }
            }
        }
        // 编辑查看楼盘信息
        if (props.isDrawerShow && (props.applyOrderId || props.transferId || props.premiseId)) {
            loading.value = true;
            const premisesInfor = await (props.applyOrderId || props.premiseId
                ? checkPremises({ applyOrderId: props.applyOrderId, premiseId: props.premiseId })
                : getDraftDetail(props.transferId));
            loading.value = false;   
            Object.assign(houseInfo, premisesInfor);
            if(!premisesInfor.auditOpinion){
                houseInfo.auditOpinion = ''
            }
            console.log('houseInfo', houseInfo)
            houseInfo.areaArr = [premisesInfor.province, premisesInfor.city, premisesInfor.area];
            houseInfo.position = `${premisesInfor.positionLng},${premisesInfor.positionLat}`;
            houseInfo.industry = premisesInfor.tabooCode ? premisesInfor.tabooCode.split(',') : [];

        }
    }
);
// 对外暴露可执行方法
defineExpose({
    resetFields,
});
</script>

<style lang="scss" scoped>
h3 {
    width: 100%;
    font-size: 16px;
    color: #333333;
    margin: 14px 0 10px 0;
}

h4 {
    margin: 0 0 -20px 0;
    z-index: 2;
}

.imgTips {
    font-size: 12px;
    color: #8c8c8c;
}

.imgUpload {
    position: relative;
    z-index: 99;
    top: -5px;
}

.imgInfo {
    display: flex;
    align-items: center;

    span {
        font-size: 14px;
        padding-left: 10px;
    }
}

.errInfo {
    width: 100%;
    height: 40px;
    padding-left: 15px;
    margin-bottom: 15px;
    line-height: 40px;
    border-radius: 0 0 0 0;
    opacity: 1;
    background: rgba(241, 90, 74, 0.1);
    font-size: 14px;
    color: #808080;

    .errIcon {
        vertical-align: middle;
    }
}

.premises-form {
    display: flex;
    justify-content: space-between;

    :deep(.el-form-item.is-required > .el-form-item__label::after) {
        content: '*';
        color: var(--el-color-danger);
        margin-left: 3px;
    }

    :deep(.el-form-item__content) {
        width: 280px;
    }

    :deep(.el-form-item) {
        margin-right: 0;
    }

    :deep(.el-input__inner) {
        height: 32px !important;
    }

    .imgUpload {
        width: 100%;
        height: 66px;
        padding: 0 15px;
        background: #ffffff;
        border-radius: 4px 4px 4px 4px;
        opacity: 1;
        border: 1px solid #d9d9d9;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        margin-top: -10px;
    }

    .upload-demo {
        margin-top: -3px;
    }

    .upload-box {
        margin-bottom: 5px;
        width: 100%;

        :deep(.el-form-item__content) {
            width: 100%;
            display: block;
        }
    }

    .more {
        width: 100%;
        text-align: center;
        font-size: 14px;
        margin-top: 20px;
        cursor: pointer;

        .moreIconClass {
            vertical-align: middle;
        }
    }
}
</style>
